package com.jin.webvideo.externalInterfaces.spi.videosearch;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.jin.webvideo.base.util.CollectionsUtil;
import com.jin.webvideo.externalInterfaces.entity.Filmography;
import com.jin.webvideo.externalInterfaces.entity.FilmographyInfo;
import com.jin.webvideo.externalInterfaces.entity.Participation;
import com.jin.webvideo.externalInterfaces.entity.ParticipationMate;
import com.jin.webvideo.externalInterfaces.iqiyi.IQIYIUtil;
import com.jin.webvideo.externalInterfaces.iqiyi.Result;
import com.jin.webvideo.base.spi.InterfaceProvider;
import com.jin.webvideo.base.spi.anno.Register;
import com.jin.webvideo.util.base.StringUtil;
import com.jin.webvideo.util.base.URLUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Register(name = "iqiyi")
public class IQIYISearchInterface extends SearchInterface {
    private static final String URL = "https://pcw-api.iqiyi.com/strategy/pcw/data/soBaseCardLeftSide?pageNum=%pageNum%&pageSize=%pageSize%&key=%key%&duration_level=0&need_qc=0&site_publish_date_level=&site=&mode=1&bitrate=&af=1";
    String URI = "https://pcw-api.iqiyi.com/strategy/pcw/data/soBaseCardLeftSide?type=list&pageNum=%pageNum%&pageSize=%pageSize%&mode=11&data_type=6;mustnot,20;mustnot,1&graph_type=1_1_2_-1&real_query=%key%&entity_name=%key%&pf=1&p=10&need_condense=1";

    private int total = -1;
    public IQIYISearchInterface(InterfaceProvider provider) {
        super(provider);
    }

    @Override
    protected List<Filmography> search(String key, String[] tags, int pageNo, int pageSize) throws Exception {
        List<Filmography> filmographies = getResult(key, tags, String.valueOf(pageNo), String.valueOf(pageSize));
        this.total = filmographies.size();
        return filmographies;
    }

    @Override
    protected int total(String key, String[] tags) throws Exception {
        return this.total;
    }

    public List<Filmography> getResult(String key, String[] channel, String pageNum, String pageSize) throws Exception {
        List<String> channels = Arrays.asList(channel);
        List<Filmography> list = getResult(key, channels, pageNum, pageSize, URI);
        for (Filmography temp : list){
            ParticipationMate mate = temp.getMate();
            if (null != mate){
                str2Participations(mate.getActor(), temp.getPlatform());
                str2Participations(mate.getDirector(), temp.getPlatform());
                str2Participations(mate.getGuest(), temp.getPlatform());
            }
        }
        list.addAll(getResult(key, channels, pageNum, "200", URL));
        return list;
    }

    public List<Filmography> getResult(String key, List<String> channel, String pageNum, String pageSize, String url) throws Exception {
        channel = CollectionsUtil.getOrDefault(channel, Arrays.asList("电影","电视剧","动漫","综艺"));
        url = URLUtil.format(url, pageNum, pageSize, key , key);// + getChannel(channel);
        Result result = IQIYIUtil.readResult(url);
        System.out.println(url);
        List<Filmography> filmographyList = new ArrayList<>();
        try{
            if (!StringUtil.isEmpty(result.getData())){
                JSONObject jsonObject = JSONObject.parseObject(result.getData());
                JSONObject formatDate = jsonObject.getJSONObject("formatData");
                JSONArray list = formatDate.getJSONArray("list");
                filmographyList = toList(list, channel);
            }
        }
        catch (JSONException jsonException){
            jsonException.printStackTrace();
        }
        return filmographyList;
    }
    private List<Filmography> toList(JSONArray infos, List<String> videoClass){
        List<Filmography> series = new ArrayList<>();
        if (null == infos) {
            return series;
        }
        //&channel_name=&duration_level=0&need_qc=0&site_publish_date_level=&site=&mode=1&bitrate=&af=1
        //&channel_name=&duration_level=0&need_qc=0&site_publish_date_level=&site=&mode=1&bitrate=&af=1
        for (int i = 0, l = infos.size(); i < l; i ++){
            JSONObject info = infos.getJSONObject(i);
            if ( filter(info, videoClass)){
                series.add( toSeries(info) );
            }
        }
        return series;
    }
    private boolean filter(JSONObject info, List<String> videoClass){
        String tag = info.getString("tag");
        if (info != null && !StringUtil.isEmpty(tag) && videoClass.contains(tag)){
            String videoDocType = info.getString("videoDocType");
            if ("1".equals(videoDocType)){
                return true;
            }
            if ( !StringUtil.isEmpty( info.getString("g_meta") )){
                return true;
            }
        }
        return false;
    }
    private Filmography toSeries(JSONObject info){
        Filmography series = new Filmography();
        series.setId( info.getString("id") );
        series.setImgSize(info.getString("g_img_size"));
        series.setImg(getImgSrc(info.getString("g_img"), series.getImgSize()));
        series.setName(info.getString("g_title"));
        series.setUrl(reseturl(info.getString("g_main_link"), info.getString("siteId")));
        series.setDesc(info.getString("desc"));
        series.setTag(info.getString("tag"));


        int displayMode = info.getBoolean("isSource").compareTo(Boolean.FALSE);
        series.setDisplayMode(displayMode);
        series.setPlatformName(info.getString("siteName"));
        series.setPlatform(info.getString("siteId"));
        series.setVideoMate(info.getString("g_meta"));
        series.setYear(info.getString("year"));

        ParticipationMate mate = new ParticipationMate();
        mate.setActor(toParticipations(info.getJSONArray("actor")));
        mate.setDirector(toParticipations(info.getJSONArray("director")));
        mate.setGuest(toParticipations(info.getJSONArray("guest")));
        series.setMate(mate);
        series.setVideoInfos(toEpisode(info.getJSONArray("videoinfos"), info.getString("siteId"), displayMode));
        return series;
    }
    private List<FilmographyInfo> toEpisode(JSONArray jsonArray, String sitid, int displayMode){
        List<FilmographyInfo> episodes = new ArrayList<>();
        if (jsonArray != null){
            for (int i = 0, l = jsonArray.size(); i < l; i ++){
                JSONObject info = jsonArray.getJSONObject(i);
                FilmographyInfo episode = new FilmographyInfo();
                episode.setUrl( reseturl(info.getString("url"), sitid ) );
                episode.setId(info.getString("id"));
                episode.setNumber( info.getInteger("order") );
                episode.setTitle( info.getString("name") );
                episode.setDate( info.getString("date") );
                episode.setPlatform(sitid);
                episode.setDisplayMode(displayMode);
                episodes.add(episode);
            }
        }
        return episodes;
    }
    private String getImgSrc(String imgUrl, String size){
        int index = imgUrl.lastIndexOf(".");
        if (index == -1 || size == null){
            return imgUrl;
        }
        String base = imgUrl.substring(0, index);
        String[] sizes = size.split(",");
        if (sizes.length < 0){
            return imgUrl;
        }
        size = sizes[0];
        return String.format("%s_%s%s", base, size, imgUrl.substring(index));
    }
    private List<Participation> toParticipations(JSONArray names){
        List<Participation> actors = new ArrayList<>();
        if (names != null){
            for (int i = 0, l = names.size(); i < l; i ++ ){
                Participation actor = new Participation();
                actor.setName(names.getString(i));
                actors.add(actor);
            }
        }
        return actors;
    }
    private void str2Participations(List<Participation> participations, String platform){
        if (null == participations){
            return;
        }
        for (Participation participation: participations ){
            String name = participation.getName();
            if (StringUtil.isEmpty(name)){
                continue;
            }
            try{
                JSONObject obj = JSONObject.parseObject(name);
                participation.setName(obj.getString("name"));
                participation.setImg(obj.getString("image_url"));
                participation.setPlatform(platform);
                participation.setId(obj.getString("id"));
            }
            catch (JSONException e){
                participation.setName(name);
            }
        }
    }
    private String reseturl(String url, String platform){
        url = URLUtil.https(url);
        if ("m1905".equals(platform)){
            return url.replace("m1905", "1905");
        }
        return url;
    }
}
